package com.heima.admin.service.Impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.admin.mapper.AdUserMapper;
import com.heima.admin.service.AdUserService;
import com.heima.common.exception.CustException;
import com.heima.model.admin.dtos.AdUserDTO;
import com.heima.model.admin.pojos.AdUser;
import com.heima.model.admin.vo.AdUserVO;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.utils.common.AppJwtUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.lang.reflect.InvocationTargetException;
import java.util.Date;
import java.util.HashMap;
@Service
@Slf4j
public class AdUserServiceImpl extends ServiceImpl<AdUserMapper, AdUser> implements AdUserService {
    @Override
    public ResponseResult login(AdUserDTO dto) throws InvocationTargetException, IllegalAccessException {
//        1. 检验密码，用户名是否存在
        if (StringUtils.isBlank(dto.getName())||StringUtils.isBlank(dto.getPassword())){
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST,"用户不存在");
        }
        //去数据库查询用户
        String name = dto.getName();
        LambdaQueryWrapper<AdUser> wrapper = Wrappers.lambdaQuery();
        wrapper.eq(AdUser::getName,name);
        AdUser adUser = this.getOne(wrapper);
        //判断用户是否存在
        if (adUser==null){
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST,"用户或者密码错误");
        }
        String password = adUser.getPassword();
        String salt = adUser.getSalt();
        String newPwd = DigestUtils.md5DigestAsHex((dto.getPassword() + salt).getBytes());
//
//        2. 检查密码是否正确
        if (!password.equals(newPwd)){
            CustException.cust(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR);
        }

//        3. 检查用户状态是否有效
        if(adUser.getStatus()!=9){
            CustException.cust(AppHttpCodeEnum.LOGIN_STATUS_ERROR,"用户的状态不对");
        }

//        4. 修改最近登录时间
        adUser.setLoginTime(new Date());
        updateById(adUser);

//        5. 颁发token,将token，还有user发给浏览器，让浏览器保存
        String token = AppJwtUtil.getToken(adUser.getId().longValue());
        AdUserVO adUserVO = new AdUserVO();
        BeanUtils.copyProperties(adUser,adUserVO);
        HashMap map = new HashMap<>();
        map.put("token",token);
        map.put("user",adUserVO);

        return ResponseResult.okResult(map);
    }
}
